<?php
namespace Handler;

use App\Common;
use Core\Model;
use Core\TbRedis;
use Helper\LBS;
use L\Notify;

class ServerHttp{
    private $mpid;//当前进程ID
    private $redis;
    protected $ouibase;
    private $db;
    private $upconfig;

    public function __construct(){
        $this->mpid = posix_getpid();

        //oui内存对照库- key是Assignment  value --uid
        $this->ouibase = new  \Swoole\table(65535);
        $this->ouibase->column('uid', \Swoole\table::TYPE_INT, 8);
        $this->ouibase->column('ouiname', \Swoole\table::TYPE_STRING, 200);
        $this->ouibase->create();
        $this->upconfig = require_once ROOT . '/config/upgrade.config.php';
        $this->db =  Model::init("httpinit");
        $this->redis = TbRedis::init("httpinit");
		$this->requestType = [
		    'leidalist'=>'getleidaconfiglist',
		    'init'=>'gettblist',
            'time'=>'gettime',
            'gettb'=>'getnowtbinfo',
            'editupfile'=>'getupfilelist',
		    'tbinfo'=>'gettbinfo',
            'tbloc'=>'getTbLocation',
            'tblocbase'=>'getTbLocationBase',
            'baselist'=>'getLocationBaselist',
            'leidainfo'=>'leidainfo',
            'tbkwd'=>'tbseachlist',
            'devlist'=>'gettbdevlist',
            'cfglist'=>'tbconfiglist',
            'setugtstop'=>'setRfurgentStop',
            'closetb'=>'closetbclient',
		];
    }

    public function onRequest($request,$response){
        $response->header("Content-Type", "text/html; charset=utf-8");
        $response->header('Access-Control-Allow-Origin', '*');//http://10.10.10.32:8020
        $response->header('Connection', 'keep-alive');//close
//        $response->header('Access-Control-Allow-Methods:POST');
//        $response->header('Access-Control-Allow-Headers:x-requested-with,content-type');

        try{
            $thisdb = Model::init('http_request');

            /**
             * 将所有的请求分发到控制器中
             * do 控制器名称
             * action 方法名称
             */
            if (!empty($request->get['action']) && !empty($request->get['do'])) {
                $namespace = 'App\Controller\\';
                $className = $namespace . $request->get['do'] . 'Controller';

                if (!class_exists($className)) {
                    return $response->end(json_encode(Common::error('请求参数错误1!')));
                }

                $class = new $className($request, $response);

                if (!method_exists($class, $request->get['action'])) {
                    return $response->end(json_encode(Common::error('请求参数错误2!')));
                }

                // 如果有数据返回则将数据发送给浏览器，否则不进行处理
                $return = call_user_func([$class, $request->get['action']]);

                if ($return) $response->end(json_encode($return));

                return;
            }

            //dump($request->get);


            if(!isset($request->get['do'])){
                $response->end($this->MakeJsonResult('FILE'));
            }else{
                $type = $request->get['do'];
                if(!array_key_exists($type,$this->requestType)){
                    $response->end($this->MakeJsonResult('FILE'));
                }else{
                    $param = [];
                    foreach($request->get as $key =>$value){
                        $param[$key]=$value;
                    }

                    $method = $this->requestType[$type];

                    $param['fd']=$request->fd;
                    $result = $this->$method($param,$thisdb);
                    if(!$result || (isset($result['errocode']) && $result['errocode']>0)){
                        $response->end($this->MakeJsonResult('FALSE',$result,0,'param wrong or return false!'));
                    }else
                        $response->end($this->MakeJsonResult('SUCCESS',['Result'=>$result]));

                }

            }
        }catch (Exception $e) {
            echo $e->getMesasge();
            $response->end($this->MakeJsonResult('FALSE',[],$e->getCode(),$e->getMessage()));
        }
    }

    public function onStart($server){
        cli_set_process_title('Http_server');

        $datas = $this->db->select('oui',  ["id", "Assignment","OrganizationName"]);
        if(!empty($datas)){
            foreach($datas as $item)
            {
                $this->ouibase->set(strtoupper($item['Assignment']), array('uid' => $item['id'],'ouiname'=>$item['OrganizationName']));
            }
        }


        //$notify = new Notify(ROOT . '/src/');
        //$notify->addEvent($server);

        echo " http server start\n";
    }

    public function getleidaconfiglist(){
        return array(
            'objitem1'=>[
                "name"=>"16服务器",
                "wsIp"=>"123.58.43.16",
                "wsPort"=>"9501",
                "ajaxIp"=>"123.58.43.16",
                "ajaxPort"=>"9506"
            ],
            'objitem2'=>[
                "name"=>"122服务器旧版",
                "wsIp"=>"103.251.36.122",
                "wsPort"=>"9501",
                "ajaxIp"=>"103.251.36.122",
                "ajaxPort"=>"9506"
            ],
            'objitem2'=>[
                "name"=>"122考勤服务器",
                "wsIp"=>"103.251.36.122",
                "wsPort"=>"9801",
                "ajaxIp"=>"103.251.36.122",
                "ajaxPort"=>"9806"
            ],
            'objitem1'=>[
                "name"=>"122新协议服务器",
                "wsIp"=>"103.251.36.122",
                "wsPort"=>"9701",
                "ajaxIp"=>"103.251.36.122",
                "ajaxPort"=>"9706"
            ]
        );
    }
    public function gettime($request,$thedb){
        return ['svrtime'=>time()];
    }

    public function tbseachlist($request,$thedb)
    {
        if(!isset($request) || empty($request)|| !isset($request['query'])) return false;
        $kw =$request['query'];// $request->get('query');
//        $devmac=$req->get['devmac'];
        $arr = [];
        foreach ($this->redis->keys('DZ*'.$kw) as $ky) {
            if (! strpos($ky, ".")) {
                $arr[] = array('deviceID' => $ky,
                    'value' => $ky,
                    'label' => $ky,
                    'status' => $this->redis->hGet($ky, 'status'));
            }
        }
        return $arr;
//        echo json_encode($arr);
    }

    public function tbconfiglist($request,$thedb)
    {
        $arr = [];
        foreach ($this->redis->keys('DZ*') as $ky) {
            if (! strpos($ky, ".")) {
                $cfginfo = $this->redis->hGetall($ky);
                if (isset($cfginfo['cfgfd']) && !empty($cfginfo['cfgfd'])) {
                    $arr[] = array('deviceID' => $ky,
                        'port' => $cfginfo['cfgserverport'],
                        'lasttime' => date('Y-m-d H:i:s', $cfginfo['cfgcreatetime'])
                    );
                }
            }
        }
        return $arr;
    }

    public function leidainfo($param,$thedb){
        if(!isset($param) || empty($param)|| !isset($param['devmac'])) return false;
        if(!isset($param['tbid'])){
            if(!isset($param['tbmac'])) return false;
            $param['tbid']= $thedb->get("device","id", array("mac"=> $param['tbmac']));
        }

        if(!isset($param['tbmac']))
            $param['tbmac']= $thedb->get("device","mac", array("id"=> $param['tbid']));

        $param['devtype']=!isset($param['devtype'])?'a001':$param['devtype'];

        if (!in_array($param['devtype'], ['a000', 'a001', 'a002'])) return false;

        $devid=$this->redis->hget(DzDataType($param['devtype']).'_'.$param['devmac'], 'devid');

        if($param['devtype']=='a001'){
            $apmac = substr($param['devmac'], 0, 6);

            $macouname=$this->ouibase->get(strtoupper($apmac),'ouiname');
        }

        $macouname=isset($macouname)? $macouname:'未知品牌';

        try{

            $row=array();
            $devrkey=$param['devtype'].'.'.$param['devmac'].'.'.$param['tbid'] ;
            if($this->redis->exists($devrkey)) {
                $nows=$this->redis->hGetall($devrkey);
//var_dump($nows);
                $rowsdata=json_decode($nows['data'],true);
                $ifurgrntrf=0;
                if($param['devtype']=='a002' && $this->redis->exists("UrRF_".$param['devmac'])){
                    $ifurgrntrf= $this->redis->hGet("UrRF_".$param['devmac'],'urgentStatus');
                }

                $row[] = array(
                    'tbid' => $param['tbid'],
                    'tbmac' => $param['tbmac'],
                    'type' => $param['devtype'],
                    'history' => 1,
                    'rssi' => $rowsdata['rssi'],
                    'sendRssi'=>isset( $rowsdata['sendRssi'])?$rowsdata['sendRssi']:$rowsdata['rssi'],
                    'devkey' => $param['devmac'],
                    'dv_brand' => $macouname,
                    'time' =>date('Y-m-d H:i:s', $nows['time']),
                    'mac' => $param['devmac'],
                    'find' => 1,
                    'urgentStatus'=>0
                );
            }

            $tbList= $thedb->select($param['devtype'],"*", array("mac"=>$param['devmac'],"time[>=]" => time()-300,"tbid"=>$param['tbid'],'ORDER'=>['time'=>'DESC']));

            if($tbList) {
                foreach ($tbList as $k => $r) {
                    $row[] = array(
                        'tbid' => $param['tbid'],
                        'tbmac' => $param['tbmac'],
                        'type' => 'a001',
                        'history' => 1,
                        'rssi' => $r['rssi'],
                        'sendRssi'=>isset( $r['sendRssi'])?$r['sendRssi']:$r['rssi'],
                        'devkey' => $param['devmac'],
                        'dv_brand' => $macouname,
                        'time' => date('Y-m-d H:i:s', $r['time']),
                        'mac' => $param['devmac'],
                        'urgentStatus'=>isset( $r['urgentStatus'])?$r['urgentStatus']:0,
                        'find' => 1
                    );
                }
            }
//            $result->closeCursor();
//            $result=null;

            return $row;

        } catch (\Exception $e) {
            return [];
        }
    }


    public function getTbLocation($param,$thedb)
    {
        if (!isset($param) || empty($param) || !isset($param['devmac'])) return false;

        $tbloction = $this->redis->hGet($param['devmac'], 'location');
        $loctionlist = json_decode($tbloction,true);
        if(isset($loctionlist['time']) && ((time()-$loctionlist['time'])<=LOCATION_INTERVAL)) {
            $loctionlist['time']=date('Y-m-d H:i:s',$loctionlist['time']);
            return $loctionlist;
        }
        else{
            $param['yes']=1;
            return $this->getLocationBaselist($param,$thedb);
        }

        return $loctionlist;

    }


    /**
     * 获取探霸以及探霸所连基站的数据信息
     * @param array $param
     * @param Model $db
     * @return array|bool|mixed
     */
    public function getTbLocationBase($param, $db)
    {
        if (!isset($param) || empty($param) || !isset($param['devmac'])) return false;

        if($this->redis->hGet($param['devmac'],'cfgstatus')==0)
            return  array('errocode'=>2,'errotext'=>'设备不在线！');

        $tbloction = $this->redis->hGet($param['devmac'], 'location');
        $loctionlist = json_decode($tbloction,true);
        // 去掉20秒请求返回原数据字符串问题， 暂时屏蔽该段代码(lvzh)
        if(false && isset($loctionlist['time']) && ((time()-$loctionlist['time'])<=LOCATION_INTERVAL)) {
            $loctionlist['time']=date('Y-m-d H:i:s',$loctionlist['time']);
            if($this->redis->hGet($param['devmac'], 'locationbase')) {
                //var_dump($this->redis->hGet($param['devmac'], 'locationbase'));
                return $this->redis->hGet($param['devmac'], 'locationbase');
            }
        }

        $lbsData = [];
        // 五分钟有效期内，读取缓存中的探霸位置
        if ($lbsLocation = $this->redis->get($param['devmac'] . '_LBS')) {
            $lbsData = json_decode($lbsLocation, true);
        } else{
            $cmddata=array(
                'type'=>'command',
                'wsfd'=>$param['fd'],
                'command' => 'getlbslocbase',
                'from' => 'httpserver',
                'deviceid'=> $param['devmac'],
                'time' =>date('Y-m-d H:i:s',time()),
                'data' =>['deviceid'=> $param['devmac']]
            );
            $this->redis->lPush('command', json_encode($cmddata));
            $i=0;
            while (true) {
                // 也许一开始就会有数据，先尝试读取数据后再sleep，这样能够更快的相应客户端请求
                //sleep(1);
                $data = json_decode($this->redis->get('httpCcmdresult_locbase_'.$param['fd']), true);
                if (isset($data)) {
                    $this->redis->del('httpCcmdresult_locbase_'.$param['fd']);
                    var_dump($data);

                    if ($data == 2) return ['errocode' => 2, 'errotext' => '查询失败'];
                    else if ($data == 3) return ['errocode' => 3, 'errotext' => '命令不支持'];

                    $data=LBS::parse($data);

                    var_dump($data);

                    break;
                }
                //echo 2;
                var_dump('get data again!');
                sleep(1);
                if($i>30) break;
                $i++;
            }

            if($i>30)
                return  array('errocode'=>3,'errotext'=>'查询超时！');
        }

        // 1分钟内不变更探霸所连基站
        if (!empty($data)) {
            $this->redis->setex($param['devmac'] . '_LBS', 1 * 60, json_encode($data));
            $lbsData = $data;
        }

        echo "-----LBS--FINISH--\n";
        var_dump($lbsData);

        /*$end = microtime(true) - $start;
        echo number_format($end, 10, '.', '')." seconds";*/

        // 获取探霸地址
        // 由于前端同时需要探霸地址与探霸所连基站地址，放在一起进行返回

        // 从redis中获取探霸地址信息
        $tbLocation = $this->redis->hGet($param['devmac'], 'location');
        $locationLists = json_decode($tbLocation,true);

        // 如果探霸信息存在时间戳，且当前时间戳小于 20秒， 更新时间戳。 否则重新获取
        if(isset($locationLists['time']) && ((time() - $locationLists['time']) <= 1)) {
            $locationLists['time'] = date('Y-m-d H:i:s', $locationLists['time']);
        }
        else{
            $param['yes']=1;
            $locationLists =  $this->getLocationBaselist($param, $db);
        }

        //var_dump($param);
        echo "1111" . PHP_EOL;
        dump($loctionlist);
        $lbsData['tanba'] = $locationLists;

        //$end = microtime(true) - $start;
        //echo number_format($end, 10, '.', '')." seconds";
        //var_dump($end);
        return $lbsData;
    }

    /*public function getLocationBaselist($param,$thedb)
    {
        if(!isset($param) || empty($param)|| !isset($param['devmac'])) return false;

        if($this->redis->hGet($param['devmac'],'cfgstatus')==0)
            return  array('errocode'=>2,'errotext'=>'设备不在线！');

        $arr = [];
        $arr['deviceID'] = $param['devmac'];
        $tbid=$this->redis->hGet($param['devmac'],'id');
        $tbloction=$this->redis->hGet($param['devmac'],'location');
        $tbloctionar=json_encode($tbloction,true);
        $loctionlist =json_decode($this->redis->hGet($param['devmac'],'locationBasekust'),true) ;
        if(!isset($param['yes'])){
            if(isset($tbloctionar['time']) && ((time()-$tbloctionar['time'])<=LOCATION_INTERVAL)) {
                $loctionlist = $thedb->get('device_basehome', 'basejson',['dvid'=>$tbid]);
                if($loctionlist){
                    $retr=json_encode($loctionlist,true);
                    if($retr['time']) $retr['time']=date('Y-m-d H:i:s',$retr['time']);
                    return $retr;
                }else{
                    return $loctionlist;
                }
            }
        }

        $arr = [];
        $cmddata=array(
            'type'=>'command',
            'wsfd'=>$param['fd'],
            'command' => 'getdeviceloc',
            'from' => 'httpserver',
            'deviceid'=> $param['devmac'],
            'time' =>date('Y-m-d H:i:s',time()),
            'data' =>['deviceid'=> $param['devmac']]
        );
        $this->redis->lPush('command', json_encode($cmddata));

        //var_dump($this->redis->get('httpCommandresult_'.$param['fd']));
        $i=0;
        while (true) {
            //sleep(1);
            $data = json_decode($this->redis->get('httpCommandresult_'.$param['fd']), true);
            if (isset($data)) {
                $arr=$data;
                $this->redis->del('httpCommandresult_'.$param['fd']);
                break;
            }
            var_dump('get tb data again');
            sleep(1);
            if($i>30) break;
            $i++;
        }

        if($i>30)
            return  array('errocode'=>3,'errotext'=>'查询超时！');

        $tbloction=$this->redis->hGet($param['devmac'],'location');
        if($tbloction && !empty($tbloction) && is_array(json_decode($tbloction,true))){
            $tbloction= array_merge(json_decode($tbloction,true),['time'=>date('Y-m-d H:i:s',time())]);
        }else
            return  array('errocode'=>4,'errotext'=>'没有发现探霸位置信息！');

        if(isset($arr['time'])) $arr['time']=date('Y-m-d H:i:s',$arr['time']);
        return isset($param['yes'])?$tbloction:$arr;
    }*/

    public function getLocationBaselist($param,$thedb)
    {
        if(!isset($param) || empty($param)|| !isset($param['devmac'])) return false;

        if($this->redis->hGet($param['devmac'],'cfgstatus')==0)
            return  array('errocode'=>2,'errotext'=>'设备不在线！');

        $arr = [];
        $arr['deviceID'] = $param['devmac'];
        $tbid=$this->redis->hGet($param['devmac'],'id');
        $tbloction=$this->redis->hGet($param['devmac'],'location');
        $tbloctionar=json_encode($tbloction,true);
        $loctionlist =json_decode($this->redis->hGet($param['devmac'],'locationBasekust'),true) ;
        if(!isset($param['yes'])){
            if(isset($tbloctionar['time']) && ((time()-$tbloctionar['time'])<=LOCATION_INTERVAL)) {
                $loctionlist = $thedb->get('device_basehome', 'basejson',['dvid'=>$tbid]);
                if($loctionlist){
                    $retr=json_encode($loctionlist,true);
                    if($retr['time']) $retr['time']=date('Y-m-d H:i:s',$retr['time']);
                    return $retr;
                }else{
                    echo '----------------return-----'  . PHP_EOL;
                    var_dump($loctionlist);
                    return $loctionlist;
                }
            }
        }
dump('abcd');

        $arr = [];
        $cmddata=array(
                'type'=>'command',
                 'wsfd'=>$param['fd'],
                 'command' => 'getdeviceloc',
                 'from' => 'httpserver',
                 'deviceid'=> $param['devmac'],
                 'time' =>date('Y-m-d H:i:s',time()),
                 'data' =>['deviceid'=> $param['devmac']]
        );
        $this->redis->lPush('command', json_encode($cmddata));

        $i=0;
        while (true) {
            // sleep(1);
            $data = json_decode($this->redis->get('httpCommandresult_'.$param['fd']), true);
            if (isset($data)) {
                $arr=$data;
                $this->redis->del('httpCommandresult_'.$param['fd']);
                break;
            }
            sleep(1);
            if($i>30) break;
            $i++;
        }

        dump($arr);
        if($i>30)
            return  array('errocode'=>3,'errotext'=>'查询超时！');

        $tbloction=$this->redis->hGet($param['devmac'],'location');
        dump($tbloction);
        if($tbloction && !empty($tbloction) && is_array(json_decode($tbloction,true))){
            $tbloction= array_merge(json_decode($tbloction,true),['time'=>date('Y-m-d H:i:s',time())]);
        }else
            return  array('errocode'=>4,'errotext'=>'没有发现探霸位置信息！');

        if(isset($arr['time'])) $arr['time']=date('Y-m-d H:i:s',$arr['time']);
        return isset($param['yes'])?$tbloction:$arr;
    }
	
	/**
	 * 取消RF紧急状态
	 * @param $param
	 * @param $thedb
	 * @return array|bool
	 */
    public function setRfurgentStop($param,$thedb)
    {
        if(!isset($param) || empty($param)|| !isset($param['devmac'])) return false;

        // 根据探霸MAC获取从redis中获取fd。 如果fd不存在返回false
        $fd=$this->redis->hget($param['tbmac'],'fd');
        if(!isset($fd)|| empty($fd)) return false;

        $data=array(
            'command'=>'resetRfugt',
            'tbmac'=>$param['tbmac'],
            'fd'=>$fd,
            'tagID'=>$param['devmac'],
            'data'=>[],
        );

        $ret= $this->redis->lPush('dtsvrcommand', json_encode($data));//通知主服务器关闭连接

        $this->redis->hSet("UrRF_".$param['devmac'],'urgentStatus',0);//解除状态0正常1为紧急
        $ret= $this->redis->lPush('rfurgent', json_encode(array( 'tbmac'=>$param['tbmac'],'fd'=>$fd,'tagID'=>$param['devmac'],'time'=>time())));

        return ['retcmd'=>$ret];
    }

    public function closetbclient($param,$thedb)
    {
        if(!isset($param) || empty($param)) return false;
        if(!isset($param['tbid'])){
            if(!isset($param['tbmac'])) return false;
            $param['tbid']= $thedb->get("device","id", array("mac"=> $param['tbmac']));
        }

        if(!isset($param['tbmac']))
            $param['tbmac']= $thedb->get("device","mac", array("id"=> $param['tbid']));

        $fd=$this->redis->hget($param['tbmac'],'fd');
        if(!isset($fd)|| empty($fd)) return false;
        $data=array(
            'command'=>'closeclient',
            'tbmac'=>$param['tbmac'],
            'fd'=>$fd,
            'data'=>[],
        );
        $ret= $this->redis->lPush('dtsvrcommand', json_encode($data));
        return ['retcmd'=>$ret];
    }

    function gettblist($param,$thedb){
        try{

            $tbList= $thedb->select("device",["id", "mac","status", "lastouttime"], array("status[<]" => 3,'ORDER'=>['lastouttime'=>'DESC']));

            if($tbList){
                foreach ($tbList as $k=>$v){
                    if($thedb->has('device_basehome', array("dvid" =>$v['id'])))
                        $tbList[$k]['location']= $thedb->get('device_basehome',["addressinfo", "longitude", "latitude"], array("dvid" =>$v['id']));
                    $tbList[$k]['count1']=$this->getdevnow(['tbid'=>$v['id'],'tm'=>1],$thedb);
                    //  $tbList[$k]['count5']=$this->getdevnow(['tbid'=>$v['id'],'tm'=>5]);
                }
            }
            return $tbList;
        } catch (\Exception $e) {
        sleep(5);
        }
    }

    function getnowtbinfo($param,$thedb){
        if(!isset($param['mac']) || empty($param['mac'])) return false;
        $dvinfo=   $this->redis->hGetall($param['mac']);

        $tbup['devinfo']=json_decode($dvinfo['deviceinfo'],true) ;

        $tbup1['ablity']=isset($dvinfo['ablity'])?json_decode($dvinfo['ablity'],true):[];
        $tbup1['encodetype']=isset($dvinfo['encodetype'])?$dvinfo['encodetype']:'';
        $tbup1['checktype']=isset($dvinfo['checktype'])?$dvinfo['checktype']:'';
        $tbup1['basedeviceinfo']=isset($dvinfo['basedeviceinfo'])? json_decode($dvinfo['basedeviceinfo'],true) :[] ;
        $tbup1['devinfo']=$tbup['devinfo'];
        $tbup['info']=$tbup1;

        $tbList= $thedb->select("uploadbase","*");
        //dump($tbList)
        dump('>>>>>>>tb');
        dump($tbList);

        dump($tbup['devinfo']['hdtype']);
        dump('<<<<<<<<tb');
        foreach ($tbList as $k=>$v){
            $hdcheck=json_decode($v['baseinfo'],true);
            if(in_array($tbup['devinfo']['hdtype'],$hdcheck['hardver']))
                $tbup['tList'][]=$v;
        }

        return $tbup;
    }

    function getupfilelist($param,$thedb){
        if(isset($param['name'])&& isset($param['opt']) && $param['opt']=='edit'){
            $fileobj=$thedb->get("uploadbase",'filename',['Id'=>$param['name']]);
            $file=$this->upconfig['uploader'].$fileobj;
            if (!file_exists($file) || !is_readable($file)){
                return  array('errocode'=>1,'errotext'=>'升级文件不存在或不可读！');
            }else{
                if (unlink($file))
                {
                    $thedb->delete("uploadbase",['Id'=>$param['name']]);
                }else
                    return  array('errocode'=>2,'errotext'=>'升级文件删除失败！');
            }

        }

        $tbup['tList']= $thedb->select("uploadbase","*");
        return $tbup;
    }


    function gettbinfo($param,$thedb){
        if(!isset($param) || empty($param)) return false;
        $tanbaid=$param['tbid'];
        $tbloction['baseinfo']= $thedb->get("device",["mac","status", "lastouttime"], array("id"=> $tanbaid));

        if($thedb->has('device_basehome', array("dvid" =>$tanbaid)))
            $tbloction['location']= $thedb->get('device_basehome',["addressinfo", "longitude", "latitude"], array("dvid" =>$tanbaid));


      //  $tbloction = $this->db->get('device_basehome',["[><]device" => ["device_basehome.dvid" => "id"]],["dvid", "mac","status", "lastouttime", "addressinfo", "longitude", "latitude"], array("dvid" => $tanbaid,'ORDER'=>['lastouttime'=>'DESC']));
        $tbloction['count1']=$this->getdevnow(['tbid'=>$tanbaid,'tm'=>1],$thedb);
        $tbloction['count5']=$this->getdevnow(['tbid'=>$tanbaid,'tm'=>5],$thedb);
        return $tbloction;
    }

    //1分钟之内探测到的总数
    function getdevnow($param,$thedb){
        if(!isset($param) || empty($param)) return false;
        $tbid=$param['tbid'];
        $tm=isset($param['tm'])?$param['tm']:1;


        $sql= "SELECT `createtime` FROM `short_a001` WHERE `tbid` ={$tbid} ORDER BY `createtime` DESC LIMIT 1 ";
        $result = $thedb->query($sql);
        while ($r = $result->fetch(2)) {
            $maxoldtime =$r['createtime'];
        }
        $result->closeCursor();
        $result=null;

        $maxoldtime =isset($maxoldtime)? $maxoldtime:time();

        $sql="SELECT COUNT(distinct deviceid) as ct FROM `short_a001` WHERE `tbid` = {$tbid} AND `createtime` >= ".($maxoldtime-60*($tm+1));

        $source = $thedb->query($sql);
        $crt=$source->fetch(1)['ct'];
        $source->closeCursor();
        $source=null;
        return $crt;
    }

    //1分钟之内探测到的次数明细,
    function gettbdevlist($param,$thedb)
        {
        if (!isset($param) || empty($param)) return false;
        $tbid = $param['tbid'];
        $tm = isset($param['tm']) ? $param['tm'] : 1;


        $sql= "SELECT `createtime` FROM `short_a001` WHERE `tbid` ={$tbid} ORDER BY `createtime` DESC LIMIT 1 ";
        $result = $thedb->query($sql);
        while ($r = $result->fetch(2)) {
            $maxoldtime =$r['createtime'];
        }
        $result->closeCursor();
        $result=null;

        $maxoldtime =isset($maxoldtime)? $maxoldtime:time();
        $sql = "select * from ( SELECT count(*) as ct, deviceid FROM `short_a001` WHERE `tbid` = {$tbid} AND `createtime` >= ".($maxoldtime-$tm*60)." GROUP BY `deviceid` LIMIT 100 )as bdc ORDER BY bdc.ct DESC LIMIT 50";
        $source = $thedb->query($sql);

        $resultArr = [];
        while ($row = $source->fetch(2)) {
            if(isset($row['deviceid'])){
                $resultArr[] = [
                    'count' => $row['ct'],
                    'devmac' => $thedb->get('stabase','mac', ['id' => $row['deviceid']]),
                    'devid' => $row['deviceid']
                ];
            }

        }

        $source->closeCursor();
        $source=null;

        return $resultArr;
    }

    function MakeJsonResult($ResultCode,$data=[],$Error=0,$ErrorMessage=''){
        $Result = ['ResultCode'=>$ResultCode];
        if($Error > 0)$Result['Error'] = $Error;
        if(!empty($ErrorMessage))$Result['ErrorMessage'] = $ErrorMessage;
        if(!empty($data) && is_array($data)){
            foreach($data as $k=>$v){
                $Result[$k] = $v;
            }
        }
        return json_encode($Result,JSON_UNESCAPED_UNICODE);
    }

}
